<template>
  <el-card>
    <div
      style="
        margin-bottom: 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      "
    >
      <el-button type="primary" @click="handleAdd">新增用户</el-button>
      <el-input
        v-model="searchKeyword"
        placeholder="搜索账号"
        clearable
        style="width: 240px"
        @clear="handleSearch"
        @change="handleSearch"
      >
        <template #prefix>
          <el-icon><i class="el-icon-search" /></el-icon>
        </template>
      </el-input>
    </div>
    <el-table :data="pagedUsers" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="userAccount" label="账号" />
      <el-table-column prop="userName" label="昵称" />
      <el-table-column prop="userAvatar" label="头像" width="80">
        <template #default="{ row }">
          <el-avatar :src="row.userAvatar" icon="el-icon-user" />
        </template>
      </el-table-column>
      <el-table-column prop="userProfile" label="简介" />
      <el-table-column prop="userRole" label="角色" width="100" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 16px 0; text-align: right">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        :page-sizes="[5, 10, 20, 50]"
      />
    </div>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="90px">
        <el-form-item label="账号" v-if="dialogTitle === '编辑用户'">
          <el-input v-model="form.userAccount" disabled />
        </el-form-item>
        <el-form-item label="昵称" prop="userName">
          <el-input v-model="form.userName" />
        </el-form-item>
        <el-form-item label="头像">
          <el-input v-model="form.userAvatar" placeholder="头像URL" />
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="form.userProfile" />
        </el-form-item>
        <el-form-item label="角色" prop="userRole">
          <el-select v-model="form.userRole" placeholder="请选择角色">
            <el-option label="用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserListAPI, deleteUserAPI, updateUserAPI, addUserAPI } from '@/api/userAPI'

const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')
const users = ref([])
const form = reactive({
  id: null,
  userAccount: '',
  userName: '',
  userAvatar: '',
  userProfile: '',
  userRole: 'user',
  phone: '',
  email: '',
  createTime: '',
})

const searchKeyword = ref('')

const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
  getUserList()
}

const getUserList = async () => {
  const res = await getUserListAPI({
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    id: searchKeyword.value,
  })
  users.value = res.data.records
}

const formRules = {
  userName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  userRole: [{ required: true, message: '请选择角色', trigger: 'change' }],
  phone: [
    {
      validator: (rule, value, callback) => {
        if (!value && !form.email) {
          callback(new Error('电话和邮箱必须至少填写一个'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  email: [
    {
      validator: (rule, value, callback) => {
        if (!value && !form.phone) {
          callback(new Error('电话和邮箱必须至少填写一个'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
}
const formRef = ref(null)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = computed(() => users.value.length)
const pagedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return users.value.slice(start, start + pageSize.value)
})

function handleAdd() {
  dialogTitle.value = '新增用户'
  Object.assign(form, {
    id: null,
    userAccount: '',
    userName: '',
    userAvatar: '',
    userProfile: '',
    userRole: 'user',
    phone: '',
    email: '',
    createTime: '',
  })
  dialogVisible.value = true
}

function handleEdit(row) {
  dialogTitle.value = '编辑用户'
  Object.assign(form, row)
  dialogVisible.value = true
}

function handleDelete(row) {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    type: 'warning',
  }).then(() => {
    deleteUserAPI(row.id).then(() => {
      ElMessage.success('删除成功')
      getUserList()
    })
  })
}

function handleSubmit() {
  formRef.value.validate((valid) => {
    if (!valid) return
    if (form.id) {
      updateUserAPI(form)
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success('编辑成功')
            getUserList()
          } else {
            ElMessage.error(res.message || '编辑失败')
          }
        })
        .catch(() => {
          ElMessage.error('编辑失败，请稍后再试')
        })
    } else {
      addUserAPI(form)
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success('新增成功')
            getUserList() // 刷新用户列表
          } else {
            ElMessage.error(res.message || '新增失败')
          }
        })
        .catch(() => {
          ElMessage.error('新增失败，请稍后再试')
        })
    }
    dialogVisible.value = false
  })
}

const handlePageChange = (val) => {
  currentPage.value = val
  getUserList()
}
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getUserList()
}

onMounted(() => {
  getUserList()
})
</script>

<style scoped>
.el-avatar {
  background: #f5f5f5;
}
</style>
